package com.huxiu.yd;

import com.huxiu.yd.net.model.Category;
import com.huxiu.yd.utils.ImageUtils;
import com.huxiu.yd.utils.Utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.Adapter;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by yao on 15/8/28:下午9:24.
 */
public class PublishSpareActivity extends Activity implements OnClickListener {

    private static final int MAX_PIC_COUNT = 8;

    @InjectView(R.id.back)
    ImageView back;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.right_image)
    ImageView rightImage;

    @InjectView(R.id.right_text)
    TextView rightText;

    @InjectView(R.id.addphoto)
    ImageView addphoto;

    @InjectView(R.id.recycler)
    RecyclerView recycler;

    @InjectView(R.id.detail_button)
    TextView detailButton;

    @InjectView(R.id.unwrapped_button)
    RadioButton unwrappedButton;

    @InjectView(R.id.wrapped_button)
    RadioButton wrappedButton;

    @InjectView(R.id.use_status_radio_group)
    RadioGroup useStatusRadioGroup;

    @InjectView(R.id.quality_button)
    TextView qualityButton;

    @InjectView(R.id.price_button)
    EditText priceButton;

    @InjectView(R.id.next_step_button)
    TextView nextStepButton;

    LinearLayoutManager mLinearLayoutManager;

    private int quality = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_spare);
        ButterKnife.inject(this);
        back.setOnClickListener(this);
        title.setText(R.string.publish_spare_item);
        rightImage.setVisibility(View.GONE);
        rightText.setVisibility(View.GONE);
        addphoto.setOnClickListener(this);
        detailButton.setOnClickListener(this);
        qualityButton.setOnClickListener(this);
        priceButton.setOnClickListener(this);
        nextStepButton.setOnClickListener(this);
        mLinearLayoutManager = new LinearLayoutManager(this);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recycler.setLayoutManager(mLinearLayoutManager);
        adapter = new GalleryAdapter();
        recycler.setAdapter(adapter);
        recycler.setVisibility(View.GONE);
    }

    @Override
    protected void onDestroy() {
        images.clear();
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.addphoto:
                if (images.size() < MAX_PIC_COUNT) {
                    ImageUtils.takeOrChoosePhoto(this, ImageUtils.TAKE_OR_CHOOSE_PHOTO);
                } else {
                    //TODO
                }
                break;
            case R.id.image: {
                final Integer tag = (Integer) v.getTag();
                if (tag.intValue() == 0) {
                    ImageUtils.takeOrChoosePhoto(this, ImageUtils.TAKE_OR_CHOOSE_PHOTO);
                } else {
                    new AlertDialog.Builder(this)
                            .setMessage("删除此照片?")
                            .setNegativeButton(android.R.string.cancel, null)
                            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    images.remove(tag.intValue() - 1);
                                    if (images.size() == 0) {
                                        recycler.setVisibility(View.INVISIBLE);
                                        addphoto.setVisibility(View.VISIBLE);
                                    }
                                    adapter.notifyDataSetChanged();
                                }
                            }).show();
                }
            }
            break;
            case R.id.quality_button:
                new AlertDialog.Builder(this)
                        .setSingleChoiceItems(getResources().getStringArray(R.array.quality), -1,
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        int selectedPosition = ((AlertDialog) dialog)
                                                .getListView().getCheckedItemPosition();
                                        quality = 10 - selectedPosition;
                                        qualityButton.setText(getResources()
                                                .getStringArray(R.array.quality)[selectedPosition]);
                                        qualityButton.setTextColor(getResources().getColor(R.color.dark_text));
                                        dialog.dismiss();
                                    }
                                }).setNegativeButton(android.R.string.cancel, null).show();
                break;
            case R.id.detail_button:
                startActivityForResult(new Intent(this, CategoryPickerActivity.class), 0);
                break;
            case R.id.next_step_button:
                if (!inputValid()) {
                    return;
                }
                Intent intent = new Intent(this, PublishSpareActivity2.class);
                intent.putExtra("category", category);
                intent.putExtra("company", company);
                intent.putExtra("product", product);
                intent.putExtra("quality", quality);
                intent.putExtra("used", unwrappedButton.isSelected());
                intent.putExtra("price", priceButton.getText().toString());
                startActivityForResult(intent, 1);
                break;
        }
    }

    private boolean inputValid() {
        if (images.isEmpty()) {
            Utils.showToast(R.string.pls_add_image);
            return false;
        }
        if (category == null) {
            Utils.showToast(R.string.pls_select_category);
            return false;
        }
        if (company == null) {
            Utils.showToast(R.string.pls_select_company);
            return false;
        }
        if (product == null) {
            Utils.showToast(R.string.pls_select_product);
            return false;
        }
        if (quality == 0) {
            Utils.showToast(R.string.pls_input_spare_quality);
            return false;
        }
        if (TextUtils.isEmpty(priceButton.getText().toString())) {
            Utils.showToast(R.string.pls_add_price);
            return false;
        }
        return true;
    }

    class GalleryViewHolder extends ViewHolder {

        ImageView imageView;

        View marginView;

        public GalleryViewHolder(View itemView) {
            super(itemView);
            imageView = (ImageView) itemView.findViewById(R.id.image);
            marginView = itemView.findViewById(R.id.space);
        }
    }

    public static ArrayList<Bitmap> images = new ArrayList<>();

    private GalleryAdapter adapter;

    class GalleryAdapter extends Adapter<GalleryViewHolder> {

        @Override
        public GalleryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = getLayoutInflater()
                    .inflate(R.layout.spare_item_gallery_item_view2, parent, false);
            return new GalleryViewHolder(view);
        }

        @Override
        public void onBindViewHolder(GalleryViewHolder holder, int position) {
            holder.imageView.setOnClickListener(PublishSpareActivity.this);
            holder.imageView.setTag(Integer.valueOf(position));
            if (position == 0) {
                holder.imageView.setImageResource(R.drawable.addphoto_button);
            } else {
                holder.imageView.setImageBitmap(images.get(position - 1));
            }
            holder.marginView
                    .setVisibility(position == images.size() ? View.GONE : View.VISIBLE);
        }

        @Override
        public int getItemCount() {
            return images.size() + 1;
        }
    }

    private Category category;

    private Category company;

    private Category product;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case 0:
                StringBuilder sb = new StringBuilder();
                if (data.hasExtra("category")) {
                    category = (Category) data.getSerializableExtra("category");
                    sb.append(category.name);
                }
                sb.append("·");
                if (data.hasExtra("company")) {
                    company = (Category) data.getSerializableExtra("company");
                    sb.append(company.title);
                } else {
                    sb.append("厂商");
                }
                sb.append("·");
                if (data.hasExtra("product")) {
                    product = (Category) data.getSerializableExtra("product");
                    sb.append(product.name);
                } else {
                    sb.append("产品");
                }
                detailButton.setText(sb.toString());
                detailButton.setTextColor(getResources().getColor(R.color.dark_text));
                break;
            case 1:
                finish();
                break;
            case ImageUtils.TAKE_OR_CHOOSE_PHOTO:
                File f = ImageUtils.getPhotoFromResult(this, data);
                ImageUtils.doCropPhoto(this, f);
                return;
            case ImageUtils.PHOTO_PICKED_WITH_DATA:
                Bitmap bitmap = ImageUtils.getCroppedImage();
                if (bitmap == null) {
                    return;
                }
                images.add(bitmap);
                addphoto.setVisibility(View.GONE);
                recycler.setVisibility(View.VISIBLE);
                adapter.notifyDataSetChanged();
                break;
        }
    }
}
